<template>
  <!-- 外层容器 -->
  <div class="layout" :class="[isAdmin ? 'admT' : 'admF', sidebarLayoutClass]">
    <!-- 主内容区域，包含地图和绝对定位的元素 -->
    <div class="main-content">
      <!-- 地图容器 -->
      <div id="map" class="map"></div>

      <!-- 地图坐标层级信息 -->
      <div class="last-message-box">
        <div class="last-message">
          {{ mousePointlat }}，{{ mousePointlng }}，层级：{{ zoom }}
        </div>
      </div>

      <!-- 顶部悬浮工具栏 -->
      <div class="floating-toolbar" :class="{ 'toolbar-collapsed': isToolbarCollapsed }">
        <div class="toolbar-item" @click="toggleSearchBox" v-if="!showSearchBox">
          <el-icon><Search /></el-icon>
          <span>搜索</span>
        </div>
        <div class="toolbar-item" @click="showEnforcementShips" v-if="!showSearchBox">
          <el-icon><Ship /></el-icon>
          <span>执法船</span>
        </div>
        <div class="toolbar-item" @click="toggleSidebar" v-if="!showSearchBox">
          <el-icon><Menu /></el-icon>
          <span>菜单</span>
        </div>
        <div class="toolbar-collapse" @click="toggleToolbar">
          <el-icon><Tools /></el-icon>
        </div>
      </div>

      <!-- 搜索框 -->
      <div class="search-box" v-if="showSearchBox">
        <div class="search-input">
          <el-icon><Search /></el-icon>
          <input type="text" placeholder="请输入船名、MMSI、呼号等" v-model="searchVal" @keyup.enter="searchSub" />
          <div class="search-actions">
            <el-button type="primary" size="small" @click="searchSub">
              <el-icon><Search /></el-icon>
            </el-button>
            <el-button size="small" @click="toggleSearchBox">
              <el-icon><Back /></el-icon>
            </el-button>
          </div>
        </div>
      </div>

      <!-- 右侧按钮容器 -->
      <rightContent ref="rightContentRef" @points="getPoint" @fun="setFun" @disposeLogShow="disposeLogShow"
        @choiceShip="changeChoiceShip" :isPopup="isPopupRight" :map="map" @changeLegendType="changeLegendType"
        @resetMap="handleResetMap">
      </rightContent>

      <!-- 其他绝对定位的弹窗或信息框 -->
      <!-- 查询统计 -->
      <query-statistics :id="refsvalue"></query-statistics>
      <!-- 系统工具 -->
      <!-- AIS异常 -->
      <anomaly v-if="isAnomaly" @closeAnomaly="closeAnomaly"></anomaly>
      <!-- 弧线计算 -->
      <information v-if="isInformation" @closeInformation="closeInformation" :itemId="itemId"></information>
      <!-- 添加工作区 -->
      <workSpace v-if="isWorkSpace" @closeWork="isWorkSpace = false" />
      <!-- 未执行计划 -->
      <plan v-if="isPlan" @closePlan="isPlan = false" />
      <!-- 视频监控 -->
      <videoMatrix v-if="isMatrix" @closeVid="isMatrix = false" />
      <!-- 右侧弹窗合集 -->
      <collection v-if="isCollection" :map="map" :list="chuan" :Collection="Collection"
        @closeCollection="isCollection = false"></collection>
      <!-- 历史预警弹窗 -->
      <historical ref="historicalRef" :isHistor="isHistor" @closeTabData="closeTabData" :map="map" @getIsDialog="getIsDialog">
      </historical>
      <dispose-log ref="disposelog" :isHistor="isDispose" @closeTabData="disposeLogClose">
      </dispose-log>
      <!-- 进出港记录 -->
      <record v-if="isRecord" @closeRecord="closeRecord"></record>
      <statistics :isStatistics="isStatistics" @closeStatis="closeStatistics"></statistics>
      <!-- 报表 -->
      <reportForms v-if="isReport" @closeReport="isReport = false" />
      <!-- 船舶档案 -->
      <shipAdmin v-if="isShipAdmin" @close="isShipAdmin = false" />

      <!-- 鼠标点击船舶信息 -->
      <shipInfo v-show="shipInfoShow" @closeShip="closeShipInfo" :info="onShip || {}" :shipInfo="{}" :map="map" ref="shipInfoRef"></shipInfo>

      <!-- 鼠标悬浮船舶信息 -->
      <div class="infoWindow" v-if="InfoShow" :style="{ left: tranLeft, top: tranTop }">
        <div class="infoWindow_title">
          {{
            infoData.chineseName ||
            infoData.englishName ||
            infoData.name ||
            infoData.mmsi
          }}
        </div>
        <div class="infoWindow_text">
          <div>MMSI:</div>
          <div>{{ infoData.mmsi }}</div>
        </div>
        <div class="infoWindow_text">
          <div>经度:</div>
          <div>{{ infoData.lat.toFixed(6) }}</div>
        </div>
        <div class="infoWindow_text">
          <div>纬度:</div>
          <div>{{ infoData.lon.toFixed(6) }}</div>
        </div>
        <div class="infoWindow_text">
          <div>航速:</div>
          <div>{{ typeof infoData.sog === 'number' ? Math.floor(infoData.sog) : 0 }}节</div>
        </div>
        <div class="infoWindow_text">
          <div>类型:</div>
          <div>{{ setShipType(infoData.shipType) }}</div>
        </div>
        <div class="infoWindow_text">
          <div>发动机状态:</div>
          <div v-if="infoData.status || infoData.status == 0">
            {{ getStatus(infoData.status) }}
          </div>
        </div>
        <div class="infoWindow_text">
          <div>更新时间:</div>
          <div>
            {{ new Date(infoData.time * 1000).toLocaleString() }}({{
              getTimeNow(new Date().getTime() - infoData.time * 1000)
            }})
          </div>
        </div>
      </div>
      <div class="infoWindow" v-if="envirShow" :style="{ left: tranLeft, top: tranTop }">
        <div class="infoWindow_title">{{ envirData.title }}</div>
        <div class="infoWindow_text">
          <div>名称:</div>
          <div>{{ envirData.title }}</div>
        </div>
        <div class="infoWindow_text">
          <div>类型:</div>
          <div>{{ envirData.type }}</div>
        </div>
        <div class="infoWindow_text">
          <div>备注:</div>
          <div>{{ envirData.remark }}</div>
        </div>
      </div>

       <!-- 预警处理对话框 -->
      <el-dialog title="预警处理" v-model="isDialogSHow" width="500px" custom-class="customDialog"
        @close="handleClose" :modal="false">
        <div class="diaBox" v-dialogDrag>
          <div class="shipInfo">
            <div class="shipInfo_item">预警船舶：{{ isDialogItem.shipName }}</div>
            <div class="shipInfo_item">MMSI：{{ isDialogItem.mmsi }}</div>
            <div class="shipInfo_item">
              预警时间：{{
                new Date(isDialogItem.warningTime * 1000).toLocaleString()
              }}
            </div>
            <div class="shipInfo_item">
              预警规则：{{ isDialogItem.eventContent }}
            </div>
            <div class="shipInfo_item">预警区域：{{ isDialogItem.address }}</div>
          </div>
          <div class="warnType">
            <div style="display: flex; align-items: center">
              <div class="title">异常类型：</div>
              <el-select v-model="isDialogItem.excepitionType" placeholder="请选择" class="elwidth"
                :disabled="isDialogSHowType == 1">
                <el-option v-for="item in typeOptions" :key="item.value" :label="item.value" :value="item.value">
                </el-option>
              </el-select>
            </div>
            <div style="display: flex; align-items: center">
              <div class="title">处置方式：</div>
              <el-select v-model="isDialogItem.handlingWay" placeholder="请选择" class="elwidth"
                :disabled="isDialogSHowType == 1">
                <el-option v-for="item in wayOptions" :key="item.value" :label="item.value" :value="item.value">
                </el-option>
              </el-select>
            </div>
          </div>
          <div class="describe">
            <div class="title">详细描述：</div>
            <div class="describeText">
              <textarea v-model="isDialogItem.detail" class="textArea" :readonly="isDialogSHowType == 1"></textarea>
            </div>
          </div>
          <div class="measure">
            <div class="title">处置措施：</div>
            <el-input v-model="isDialogItem.treatmentMeasure" placeholder="请输入内容" class="elinp"
              :readonly="isDialogSHowType == 1"></el-input>
          </div>
          <div class="warnType">
            <div style="display: flex; align-items: center">
              <div class="title">纠正情况：</div>
              <el-select v-model="isDialogItem.correctTheSituation" placeholder="请选择" class="elwidth"
                :disabled="isDialogSHowType == 1">
                <el-option v-for="item in correctOptions" :key="item.value" :label="item.value" :value="item.value">
                </el-option>
              </el-select>
            </div>
            <div style="display: flex; align-items: center">
              <div class="title">是否处罚：</div>
              <el-select v-model="isDialogItem.punish" placeholder="请选择" class="elwidth" :disabled="isDialogSHowType == 1">
                <el-option v-for="item in punishOptions" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </div>
          </div>
          <div class="measure">
            <div class="title">备注：</div>
            <el-input v-model="isDialogItem.remark" placeholder="请输入内容" class="elinp"
              :readonly="isDialogSHowType == 1"></el-input>
          </div>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="handleClose">取 消</el-button>
            <el-button type="primary" @click="submitForm" v-if="isDialogSHowType == 2">确 定</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 船舶告警通知组件 -->
      <ShipAlarmNotification ref="shipAlarmRef" />

      <!-- 执法船列表组件 -->
      <GaShipList v-if="showGaShipList" @close="closeGaShipList" />

    </div>

    <!-- 右侧侧边栏 (PopupRight) -->
    <PopupRight v-if="isPopupRight" :Popup="PopupType" :map="map" :searchList="searchList" :isCollapsed="isCollapsed"
      @closeCollection="isPopupRight = false" @isdrawer="getisdrawer" @renewData="renewData"
      @isCollapsedChange="handleCollapsedChange"></PopupRight>

  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, onBeforeUnmount, nextTick, watch, defineAsyncComponent } from 'vue';
// import type { ComponentInternalInstance } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessageBox, ElMessage } from 'element-plus';
import { useUserStore } from '@/store/modules/user';
// import { Place } from "@/utils/request";
import { getShipList, shipHistory, envList, plotList } from "@/api/map/map";
import { getToken } from "@/utils/auth";
// import Sidebar from "@/layout/components/Sidebar/index.vue";
import { updateUserPwd } from "@/api/system/user";
import { getdispose, getdisposeDetail } from "@/api/wan/realTime";
import { getWhiteList } from "@/api/shipGrouping";
import { getShipAlarm } from "@/api/wan/shipAis"; // 导入船舶告警接口
import fen from "@/assets/fen.json";

// 导入船舶追踪功能
import { initShipTracking, loadShipAisData, setFences } from './shipTracking';

// OpenLayers导入
import Map from 'ol/Map.js';
import View from 'ol/View.js';
import { defaults as Defaults } from 'ol/control.js';
import TileLayer from 'ol/layer/Tile.js';
import XYZ from 'ol/source/XYZ.js';
import VectorLayer from 'ol/layer/Vector.js';
import VectorSource from 'ol/source/Vector.js';
import { Style, Circle as CircleStyle, Fill, Stroke, Icon } from 'ol/style.js';
import { Draw, Modify, Snap, Select } from 'ol/interaction.js';
import { Point, LineString, Polygon } from 'ol/geom.js';
import Feature from 'ol/Feature.js';
import { fromLonLat, toLonLat } from 'ol/proj.js';
import Overlay from 'ol/Overlay.js';
import { getLength } from 'ol/sphere';

// 如果存在mapUtils引入冲突，我们使用原有的
import mapUtils from '@/utils/mapUtils';

// Lazy load components
const ShipAlarmNotification = defineAsyncComponent(() => import('./components/ShipAlarmNotification.vue'));
const GaShipList = defineAsyncComponent(() => import('./components/GaShipList.vue'));
const disposeLog = defineAsyncComponent(() => import('@/views/WindPower/monitor/disposeLog.vue'));
const reportForms = defineAsyncComponent(() => import('@/views/WindPower/windowPages/reportForms.vue'));
const videoMatrix = defineAsyncComponent(() => import('@/views/WindPower/video/videoMatrix.vue'));
const warningInfo = defineAsyncComponent(() => import('@/views/WindPower/windowPages/warningInfo.vue'));
const plan = defineAsyncComponent(() => import('@/views/WindPower/windowPages/plan.vue'));
const historical = defineAsyncComponent(() => import('@/views/WindPower/monitor/historical.vue'));
const record = defineAsyncComponent(() => import('@/views/WindPower/monitor/record.vue'));
const statistics = defineAsyncComponent(() => import('@/views/WindPower/monitor/statistics.vue'));
const anomaly = defineAsyncComponent(() => import('@/views/WindPower/riskWarn/anomaly.vue'));
const alarm = defineAsyncComponent(() => import('@/views/WindPower/alarm.vue'));
const searchRes = defineAsyncComponent(() => import('@/views/WindPower/searchRes.vue'));
const rightContent = defineAsyncComponent(() => import('@/views/WindPower/right-content.vue'));
const shipInfo = defineAsyncComponent(() => import('@/views/WindPower/shipInfo.vue'));
const PopupRight = defineAsyncComponent(() => import('@/views/WindPower/shipSupervision/popup.vue'));
const queryStatistics = defineAsyncComponent(() => import('@/views/WindPower/queryStatistics/index.vue'));
const information = defineAsyncComponent(() => import('@/views/WindPower/windowPages/information.vue'));
const workSpace = defineAsyncComponent(() => import('@/views/WindPower/windowPages/workspace.vue'));
const shipAdmin = defineAsyncComponent(() => import('@/views/WindPower/monitor/shipAdmin.vue'));
import InfoWindow from './components/InfoWindow.vue';
import emitter from '@/utils/bus'; // 确保导入emitter
import { Search, Ship, Menu, Tools, Back } from '@element-plus/icons-vue';

// Global T object from window
declare const window: Window & {
  T: any;
  emitter?: any; // 添加emitter到window类型定义
};

// Types
interface ShipInfo {
  id?: number;
  mmsi: string;
  name?: string;
  chineseName?: string;
  englishName?: string;
  lat?: number;
  lon?: number;
  sog?: number;
  cog?: number;
  shipType?: number;
  status?: number;
  time?: number;
  destination?: string;
  eta?: number;
  draught?: number;
  region?: string;
}

interface UserStore {
  nickname: string;
  roles: string[];
  logout: () => Promise<void>;
}

interface DialogItem {
  shipName: string;
  mmsi: string;
  warningTime: number;
  eventContent: string;
  address: string;
  excepitionType: string;
  handlingWay: string;
  detail: string;
  treatmentMeasure: string;
  correctTheSituation: string;
  punish: boolean;
  remark: string;
}

interface PunishOption {
  value: string; // 修改为string类型
  label: string;
}

// 使用Pinia store
const userStore = useUserStore();
const router = useRouter();

// Define refs for component instances
const shipAlarmRef = ref(null);
const historicalRef = ref(null);
const disposelog = ref(null);
const rightContentRef = ref(null);
const shipInfoRef = ref(null);

// Define data properties
const map = ref(null);
const Collection = ref("");
const PopupType = ref("");
const isCollection = ref(false);
const isHistor = ref(false);
const isDispose = ref(false);
const isPopupRight = ref(false);
const isCollapsed = ref(false);
const isStatistics = ref(false);
const shipInfoShow = ref(false);
const isShipAdmin = ref(false);
const showSearchBox = ref(false); // 搜索框显示状态

// Ship info related data
const onShip = ref<ShipInfo | null>(null);
const InfoShow = ref(false);
const infoData = reactive<ShipInfo>({
  mmsi: '',
  lat: 0,
  lon: 0,
  sog: 0,
  shipType: 0,
  status: undefined,
  time: 0,
  chineseName: '',
  englishName: '',
  name: ''
});

// More state variables
const refsvalue = ref("");
const isAnomaly = ref(false);
const isInformation = ref(false);
const isWorkSpace = ref(false);
const isPlan = ref(false);
const isMatrix = ref(false);
const isReport = ref(false);
const isRecord = ref(false);
const visibleUser = ref(false);
const isAdmin = ref(false);
const itemId = ref("");
const timeYMD = ref("");
const timeHMS = ref("");
const mousePointlat = ref("");
const mousePointlng = ref("");
const zoom = ref("");
const searchVal = ref("");
const chuan = ref(null);
const loading = ref(false);
const isDialog = ref(false);
const isDialogSHow = ref(false);
const isDialogSHowType = ref(2);
const isDialogItem = reactive<DialogItem>({
  shipName: '',
  mmsi: '',
  warningTime: 0,
  eventContent: '',
  address: '',
  excepitionType: '',
  handlingWay: '',
  detail: '',
  treatmentMeasure: '',
  correctTheSituation: '',
  punish: false,
  remark: ''
});
const typeOptions = ref([]);
const wayOptions = ref([]);
const correctOptions = ref([]);
const punishOptions = ref<PunishOption[]>([
  { value: 'true', label: '是' }, // 修改为字符串
  { value: 'false', label: '否' }
]);
const formPwd = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
});
const rulesPwd = reactive({
  oldPassword: [{ required: true, message: '请输入旧密码', trigger: 'blur' }],
  newPassword: [{ required: true, message: '请输入新密码', trigger: 'blur' }],
  confirmPassword: [{ required: true, message: '请确认新密码', trigger: 'blur' }]
});
const envirShow = ref(false);
const envirData = reactive({
  title: '',
  type: '',
  remark: ''
});
const tranLeft = ref('0px');
const tranTop = ref('0px');
const searchList = ref([]);
const isSidebarDrawer = ref(false); // 新增：存储侧边栏是否为抽屉模式
const showGaShipList = ref(false);

// Create computed properties
const username = computed(() => userStore.nickname || '');
const userRole = computed(() => userStore.roles?.[0] || '普通用户');

// 新增：计算布局类
const sidebarLayoutClass = computed(() => {
  if (!isPopupRight.value) {
    return ''; // 侧边栏隐藏，无特殊类
  }
  // 侧边栏显示时，根据isSidebarDrawer状态决定
  return isSidebarDrawer.value ? 'has-sidebar-mini' : 'has-sidebar';
});

// Methods
const isShowNavWAn = (typeName) => {
  if (!typeName) return;
  
  // 根据不同的类型显示不同的内容
  switch (typeName) {
    case 'statistics':
      isStatistics.value = true;
      break;
    case 'realTime':
      // 显示实时预警
      isHistor.value = true;
      break;
    // 其他类型...
    default:
      console.log('未处理的导航类型:', typeName);
  }
};

const getPoint = (val) => {
  if (!map.value) return;
  
  // 如果val是坐标对象
  if (val && typeof val === 'object' && val.lat && val.lon) {
    // 设置地图中心点
    map.value.getView().setCenter([val.lon, val.lat]);
    map.value.getView().setZoom(10.5);
  } 
  // 如果val是字符串或其他类型
  else if (val) {
    console.log('位置信息:', val);
  }
};

// 活动绘图交互
let activeDrawInteraction = null;
let activeSelectInteraction = null;
let measureTooltipElement = null;
let measureTooltip = null;

// 在import区域添加测量工具类
import { MeasureUtils, addMeasureStyles } from '@/utils/measureUtils';

// 在代码中适当位置（可能是setup或者onMounted钩子内）添加如下代码
let measureUtils: MeasureUtils | null = null;
let measureCleanupFn: (() => void) | null = null;
const isMeasuring = ref(false);

// 在map加载完成后初始化测量工具
onMounted(() => {
  // 其他初始化代码...
  
  // 等待地图初始化完成后创建测量工具
  nextTick(() => {
    if (map.value) {
      console.log('初始化测量工具组件');
      // 添加测量样式
      addMeasureStyles();
      // 创建测量工具实例
      measureUtils = new MeasureUtils(map.value);
    }
  });
});

// 添加清除测量方法
const clearMeasurements = () => {
  if (measureUtils) {
    console.log('调用清除测量功能');
    measureUtils.clearMeasurement();
    // 清除清理函数
    if (measureCleanupFn) {
      measureCleanupFn = null;
    }
    // 通知右侧内容组件测量已结束
    isMeasuring.value = false;
  }
};

// 添加重置地图方法
const resetMap = () => {
  console.log('重置地图 - 清空绘制的线段和图形');
  
  try {
    // 清除所有测量
    if (measureUtils) {
      measureUtils.clearMeasurement();
      measureCleanupFn = null;
    }
    
    // 确保清除所有可能的绘图交互
    clearDrawInteractions();
    
    // 清除向量图层中的所有要素
    if (map.value) {
      const layers = map.value.getLayers().getArray();
      layers.forEach(layer => {
        if (layer instanceof VectorLayer) {
          const source = layer.getSource();
          if (source && typeof source.clear === 'function') {
            source.clear();
          }
        }
      });
      
      // 重置地图视图到初始位置
      map.value.getView().animate({
        center: [121.9, 30.5], // 地图初始中心点
        zoom: 10.5,           // 地图初始缩放级别
        duration: 800
      });
      
      // 通知右侧内容组件测量已结束
      isMeasuring.value = false;
      
      // 显示重置成功提示
      ElMessageBox.alert('所有测量已清除，地图已返回初始位置', '地图已重置', {
        type: 'success',
        confirmButtonText: '确定'
      });
    }
  } catch (error) {
    console.error('重置地图时发生错误:', error);
    ElMessageBox.alert('重置地图过程中发生错误，请刷新页面', '错误', {
      type: 'error',
      confirmButtonText: '确定'
    });
  }
};

// 在setFun方法中添加距离和面积测量逻辑
const setFun = (val: number) => {
  if (!map.value) {
    console.error('地图未初始化');
    return;
  }
  
  if (!measureUtils) {
    console.error('测量工具未初始化');
    return;
  }
  
  console.log('开始测量操作:', val);
  isMeasuring.value = true;
  
  try {
    if (val === 1) {
      // 距离测量
      console.log('启动距离测量');
      measureCleanupFn = measureUtils.startMeasureDistance();
    } else if (val === 2) {
      // 面积测量
      console.log('启动面积测量');
      measureCleanupFn = measureUtils.startMeasureArea();
    }
  } catch (error) {
    console.error('测量操作失败:', error);
    isMeasuring.value = false;
  }
};

const disposeLogShow = () => {
  isDispose.value = true;
};

const disposeLogClose = () => {
  isDispose.value = false;
};

const changeLegendType = (val) => {
  if (map.value && typeof val === 'number') {
    // 根据传入的值切换图例类型
    console.log('切换图例类型:', val);
    // 可以在此处添加更多的图例类型处理逻辑
  }
};

const changeChoiceShip = (val) => {
  if (!val) return;
  
  console.log('选择船舶:', val);
  // 选择船舶的处理逻辑
  // 例如：显示船舶详情、高亮显示等
  if (val.name === '船舶') {
    // 处理船舶选择
  } else if (val.name === '标绘') {
    // 处理标绘选择
  }
  // 其他处理...
};

const getisdrawer = (val: boolean) => {
  isSidebarDrawer.value = val; // 更新isSidebarDrawer状态
  console.log('抽屉状态变化 (index.vue):', val);
};

const renewData = () => {
  // 刷新数据
  console.log('刷新数据');
  
  // 例如：重新获取船舶列表
  // if (map.value) {
  //   // 调用获取船舶数据的API
  //   getShipList({}).then(res => {
  //     if (res && res.data) {
  //       chuan.value = res.data;
  //       // 更新地图上的船舶标记等
  //     }
  //   }).catch(err => {
  //     console.error('获取船舶数据失败:', err);
  //   });
  // }
};

const closeAnomaly = () => {
  isAnomaly.value = false;
};

const closeInformation = () => {
  isInformation.value = false;
};

const closeRecord = () => {
  isRecord.value = false;
};

const closeStatistics = () => {
  isStatistics.value = false;
};

const closeTabData = () => {
  isHistor.value = false;
};

const getIsDialog = (val) => {
  if (val && typeof val === 'object') {
    // 处理对话框数据
    isDialogSHow.value = true;
    isDialogSHowType.value = val.type || 2;
    
    // 填充对话框数据
    if (val.data) {
      Object.assign(isDialogItem, val.data);
    }
  }
};

const searchSub = () => {
  if (!searchVal.value) {
    ElMessageBox.alert('请输入搜索内容', '提示');
    return;
  }
  
  console.log('搜索:', searchVal.value);
  
  // 设置模拟数据用于测试
  searchList.value = [{
    mmsi: searchVal.value,
    name: "测试船舶",
    chineseName: "测试船舶",
    lat: 30.5,
    lon: 121.9,
    shipType: 70,
    status: 0,
    time: Math.floor(Date.now() / 1000)
  }];
  
  // 先设置PopupType，再显示弹窗
  PopupType.value = "searchRes";
  console.log("设置PopupType:", PopupType.value);
  
  // 确保在下一个事件循环中设置isPopupRight，以便PopupType先生效
  setTimeout(() => {
    isPopupRight.value = true;
    console.log("设置isPopupRight:", isPopupRight.value);
  }, 0);
  
  /* 实际项目中应该调用API:
  searchShips(searchVal.value).then(res => {
    if (res && res.data) {
      searchList.value = res.data;
      if (searchList.value.length > 0) {
        // 显示搜索结果
        PopupType.value = "searchRes";
        setTimeout(() => {
          isPopupRight.value = true;
        }, 0);
      } else {
        ElMessageBox.alert('未找到相关数据', '提示');
      }
    }
  }).catch(err => {
    console.error('搜索失败:', err);
    ElMessageBox.alert('搜索失败，请重试', '错误');
  });
  */
};

const getTimeNow = (time: number): string => {
  const days = Math.floor(time / (1000 * 60 * 60 * 24));
  const hours = Math.floor((time % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  const minutes = Math.floor((time % (1000 * 60 * 60)) / (1000 * 60));
  const seconds = Math.floor((time % (1000 * 60)) / 1000);
  
  if (days > 0) {
    return `${days}天前`;
  } else if (hours > 0) {
    return `${hours}小时前`;
  } else if (minutes > 0) {
    return `${minutes}分钟前`;
  } else {
    return `${seconds}秒前`;
  }
};

const setShipType = (type: number | undefined): string => {
  if (!type) return '未知';
  
  if (type >= 60 && type <= 69) {
    return "客船";
  } else if (type >= 70 && type <= 74) {
    return "货船";
  } else if (type === 33) {
    return "作业船";
  } else if (type === 52) {
    return "拖船";
  } else if (type === 30) {
    return "渔船";
  } else {
    return "其他";
  }
};

const getStatus = (val: number | undefined): string => {
  if (val === undefined) return '未知';
  
  if (val === 8 || val === 0) {
    return "航行";
  } else if (val === 5 || val === 1) {
    return "停泊";
  } else {
    return "未知";
  }
};

const closeShipInfo = () => {
  shipInfoShow.value = false;
  onShip.value = null;
};

const showShipInfo = (ship: ShipInfo) => {
  onShip.value = ship;
  shipInfoShow.value = true;
};

const changePWD = () => {
  isDialog.value = true;
};

const close = () => {
  isDialog.value = false;
  formPwd.oldPassword = '';
  formPwd.newPassword = '';
  formPwd.confirmPassword = '';
};

const submit = () => {
  // 密码修改提交逻辑
};

const handleClose = () => {
  isDialogSHow.value = false;
};

const submitForm = () => {
  // 预警处理提交逻辑
};

const logout = () => {
  ElMessageBox.confirm('确定注销并退出系统吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    userStore.logout().then(() => {
      router.push(`/login`);
    });
  }).catch(() => {});
};

// 激活指定的tab
const activateTab = (tabName: string) => {
  // 如果当前已经是激活状态，则隐藏侧边栏
  if (PopupType.value === tabName && isPopupRight.value) {
    isPopupRight.value = false;
    console.log("隐藏侧边栏");
    return;
  }
  
  // 设置要显示的组件类型
  PopupType.value = tabName;
  console.log("激活Tab:", tabName);
  
  // 如果是realTime，打开预警历史记录
  if (tabName === 'realTime') {
    isHistor.value = true;
  }
  
  // 确保PopupRight组件是显示的
  if (!isPopupRight.value) {
    setTimeout(() => {
      isPopupRight.value = true;
      console.log("显示侧边栏");
    }, 0);
  }
};

// 处理船舶告警
emitter.on('handle-ship-alarm', (alarm) => {
  console.log('处理船舶告警:', alarm);
  
  // 打开预警处理对话框
  if (alarm) {
    // 显示预警处理对话框
    isDialogSHow.value = true;
    isDialogSHowType.value = 2; // 设置为编辑模式
    
    // 填充对话框数据
    isDialogItem.shipName = alarm.shipName || '';
    isDialogItem.mmsi = alarm.mmsi || '';
    isDialogItem.warningTime = alarm.createTime ? new Date(alarm.createTime).getTime() / 1000 : 0;
    isDialogItem.eventContent = alarm.eventContent || '';
    isDialogItem.address = alarm.address || '';
    
    // 默认值
    isDialogItem.excepitionType = '';
    isDialogItem.handlingWay = '';
    isDialogItem.detail = '';
    isDialogItem.treatmentMeasure = '';
    isDialogItem.correctTheSituation = '';
    isDialogItem.punish = false;
    isDialogItem.remark = '';
  }
});

// 防抖计时器
let debounceTimer: ReturnType<typeof setTimeout> | null = null;

/**
 * 防抖函数 - 限制函数调用频率
 * @param fn 需要防抖的函数
 * @param delay 延迟时间(ms)
 * @returns 防抖处理后的函数
 */
function debounce<T extends (...args: any[]) => any>(fn: T, delay: number): (...args: Parameters<T>) => void {
  return function(this: any, ...args: Parameters<T>): void {
    if (debounceTimer !== null) {
      clearTimeout(debounceTimer);
    }
    debounceTimer = setTimeout(() => {
      fn.apply(this, args);
      debounceTimer = null;
    }, delay);
  };
}

// Lifecycle hooks
onMounted(() => {
  // 直接设置初始时间显示
  const now = new Date();
  timeYMD.value = now.toLocaleDateString();
  timeHMS.value = now.toLocaleTimeString();
  
  // 将emitter挂载到window对象上，供非Vue组件使用
  window.emitter = emitter;

  // 使用nextTick确保DOM已经渲染
  nextTick(() => {
    initMap();
    
    // 延迟2秒后启动AIS数据刷新，确保地图和图层已完全初始化
    setTimeout(() => {
      startAisDataRefresh();
      console.log('AIS数据刷新已启动');
      
      // 启动船舶告警检查
      startShipAlarmCheck();
    }, 2000);
  });
});

// 组件销毁时的清理工作
onBeforeUnmount(() => {
  // 清除防抖计时器
  if (debounceTimer !== null) {
    clearTimeout(debounceTimer);
    debounceTimer = null;
  }
  
  // 清除所有InfoWindow的事件总线监听
  try {
    emitter.emit('hide-info-window');
  } catch (error) {
    console.error('清除InfoWindow失败:', error);
  }
  
  // 清除事件监听
  try {
    emitter.off('handle-ship-alarm');
  } catch (error) {
    console.error('清除事件监听失败:', error);
  }
  
  // 清除地图上可能存在的矩形工具
  try {
    if (map.value) {
      // 检查并移除所有绘图交互
      clearDrawInteractions();
      
      // 特别处理可能存在的矩形工具
      if (window.T) {
        // 获取所有矩形绘制工具并移除它们
        const allOverlays = map.value.getOverlays ? map.value.getOverlays() : [];
        if (Array.isArray(allOverlays)) {
          allOverlays.forEach((overlay: any) => {
            // 检查类名或实例类型以确定是否为矩形
            if ((overlay.CLASS_NAME && 
                (overlay.CLASS_NAME.includes('Rectangle') || 
                overlay.CLASS_NAME.includes('RectangleTool'))) ||
                (window.T && (
                  overlay instanceof window.T.Rectangle || 
                  overlay instanceof window.T.RectangleTool))) {
              map.value.removeOverlay(overlay);
            }
          });
        }
      }
    }
  } catch (error) {
    console.error('清除地图资源时发生错误:', error);
  }
  
  // 清除地图实例和事件监听
  if (map.value) {
    try {
      // 清除地图实例
      map.value.setTarget(undefined);
      map.value = null;
    } catch (error) {
      console.error('清理地图资源时发生错误:', error);
    }
  }
  
  // 清除AIS数据刷新定时器
  stopAisDataRefresh();
  
  // 清除船舶告警检查定时器
  stopShipAlarmCheck();
  
  // 清除window上挂载的emitter
  if (window.emitter) {
    window.emitter = undefined;
  }
});

// 处理重置地图事件
const handleResetMap = () => {
  console.log('处理重置地图事件');
  if (measureUtils) {
    measureUtils.clearMeasurement();
    if (measureCleanupFn) {
      measureCleanupFn();
      measureCleanupFn = null;
    }
    measureUtils.clearAllTooltips();
  }
};

// initMap function now only appears once
function initMap() {
  const mapContainer = document.getElementById('map');
  if (!mapContainer) {
    console.error('地图容器不存在');
    return;
  }

  try {
    // 创建矢量数据源和绘图图层
    const vectorSource = new VectorSource();
    
    // 创建矢量图层用于绘制
    const drawingLayer = new VectorLayer({
      source: vectorSource,
      style: new Style({
        fill: new Fill({
          color: 'rgba(64, 158, 255, 0.2)'
        }),
        stroke: new Stroke({
          color: '#409EFF',
          width: 2
        }),
        image: new CircleStyle({
          radius: 5,
          fill: new Fill({
            color: '#409EFF'
          })
        })
      })
    });

    // 天地图图层
    const source = new XYZ({
      url: 'http://t4.tianditu.com/DataServer?T=vec_w&tk=761d35504d4852532b586f4b529a6889&x={x}&y={y}&l={z}'
    });
    const tileLayer = new TileLayer({
      source: source,
      className: 'light-layer'
    });

    // 标注图层
    const sourceMark = new XYZ({
      url: 'http://t4.tianditu.com/DataServer?T=cva_w&tk=761d35504d4852532b586f4b529a6889&x={x}&y={y}&l={z}'
    });
    const tileMark = new TileLayer({
      source: sourceMark,
      className: 'label-layer'
    });

    // 创建地图对象
    map.value = new Map({
      target: 'map',
      layers: [tileLayer, tileMark, drawingLayer],
      view: new View({
        projection: 'EPSG:4326',
        center: [121.9, 30.5],
        zoom: 10.5,
        maxZoom: 20,
        minZoom: 1
      }),
      controls: Defaults({
        zoom: false,
        rotate: false
      })
    });

    // 设置地图工具中的vectorSource
    mapUtils.setMap(map.value);
    mapUtils.setVectorSource(vectorSource);

    // 确保地图完全加载后再初始化测量工具
    map.value.once('postrender', () => {
      console.log('地图渲染完成，初始化测量工具');
      // 添加测量样式
      addMeasureStyles();
      // 创建测量工具实例
      measureUtils = new MeasureUtils(map.value);
    });

    // 地图事件监听
    if (map.value) {
      // 鼠标移动事件，更新坐标显示
      map.value.on('pointermove', (e) => {
        const coordinate = e.coordinate;
        mousePointlng.value = coordinate[0].toFixed(6);
        mousePointlat.value = coordinate[1].toFixed(6);
      });

      // 缩放事件 - 更新缩放级别显示
      map.value.on('moveend', () => {
        zoom.value = map.value.getView().getZoom().toString();
      });

      // 初始化缩放级别显示
      zoom.value = map.value.getView().getZoom().toString();
      
      // 初始化船舶跟踪
      initShipTracking(map.value);
      
      // 加载电子围栏数据
      loadElectronicFences();
    }
    
  } catch (error) {
    console.error('地图初始化失败:', error);
  }
}

/**
 * 加载电子围栏数据
 * 通常这应该从后端API获取，这里为了演示使用硬编码数据
 */
const loadElectronicFences = () => {
  try {
    
    // 设置一个空的围栏数组，稍后会从API加载真实数据
    // electronicFences.value = [];
    
    // 更新AIS服务中的围栏数据
    // 确保电子围栏多边形是闭合的
    const fencesForTracking = electronicFences.value.map(fence => {
      // 如果多边形不是闭合的，添加闭合点
      const coords = [...fence.coordinates];
      if (coords.length > 0 && (coords[0][0] !== coords[coords.length-1][0] || coords[0][1] !== coords[coords.length-1][1])) {
        coords.push([coords[0][0], coords[0][1]]);
      }
      return coords;
    });
    
    console.log('向船舶跟踪模块传递围栏数据:', fencesForTracking);
    setFences(fencesForTracking);
  } catch (error) {
    console.error('加载电子围栏数据失败:', error);
  }
};

/**
 * 停止AIS数据刷新
 */
const stopAisDataRefresh = () => {
  if (aisDataRefreshInterval.value !== null) {
    clearInterval(aisDataRefreshInterval.value);
    aisDataRefreshInterval.value = null;
    console.log('AIS数据刷新已停止');
  }
};

// Watch
watch(() => searchVal.value, (newVal, oldVal) => {
  // Implementation of watch for searchVal...
});

// 切换侧边栏展开/收起状态
const toggleCollapse = () => {
  isCollapsed.value = !isCollapsed.value;
  isPopupRight.value = true; // 确保侧边栏是可见的
};

// 处理组件内部折叠状态变化
const handleCollapsedChange = (val: boolean) => {
  if (isCollapsed.value !== val) {
    isCollapsed.value = val;
  }
};

// 定义电子围栏数据类型
interface ElectronicFence {
  id: number | string;
  name: string;
  coordinates: number[][];
  // 其他围栏属性...
}

// 在data属性部分添加
const electronicFences = ref<ElectronicFence[]>([]);
const aisDataRefreshInterval = ref<number | null>(null);
const aisRefreshRate = ref(7000); // 默认30秒刷新一次
const shipAlarmInterval = ref<number | null>(null); // 船舶告警检查定时器

// 在方法部分添加以下方法
/**
 * 加载船舶AIS数据并显示在地图上
 */
const loadAisData = async () => {
  try {
    // console.log('加载AIS数据...');
    const shipList = await loadShipAisData();
    // console.log(`加载了 ${shipList.length} 条船舶数据`);
  } catch (error) {
    // console.error('加载AIS数据失败:', error);
  }
};

/**
 * 开始定时刷新AIS数据
 */
const startAisDataRefresh = () => {
  // 先清除可能存在的定时器
  stopAisDataRefresh();
  
  try {
    // 先立即加载一次
    loadAisData().catch(err => {
      console.error('初始AIS数据加载失败:', err);
    });
    
    // 设置定时刷新
    aisDataRefreshInterval.value = window.setInterval(() => {
      loadAisData().catch(err => {
        console.error('定时AIS数据加载失败:', err);
      });
    }, aisRefreshRate.value);
    
    console.log(`AIS数据刷新已启动，刷新间隔: ${aisRefreshRate.value / 1000}秒`);
  } catch (error) {
    console.error('启动AIS数据刷新失败:', error);
  }
};

/**
 * 检查船舶告警状态
 */
const checkShipAlarm = async () => {
  try {
    const res = await getShipAlarm();
    if (res.code === 200 && res.data && res.data.length > 0) {
      // 有船舶告警信息，通过ShipAlarmNotification组件显示
      if (shipAlarmRef.value) {
        shipAlarmRef.value.showAlarms(res.data);
      } else {
        // 如果组件未挂载，通过事件总线发送数据
        emitter.emit('ship-alarm-triggered', res.data);
      }
    }
  } catch (error) {
    console.error('检查船舶告警失败:', error);
  }
};

// 开始船舶告警检查
const startShipAlarmCheck = () => {
  // 先清除可能存在的定时器
  stopShipAlarmCheck();
  
  // 先立即检查一次
  checkShipAlarm().catch(err => {
    console.error('初始船舶告警检查失败:', err);
  });
  
  // 设置定时检查 (每3分钟检查一次)
  shipAlarmInterval.value = window.setInterval(() => {
    checkShipAlarm().catch(err => {
      console.error('定时船舶告警检查失败:', err);
    });
  }, 3 * 60 * 1000); // 3分钟
  
  console.log('船舶告警检查已启动，检查间隔: 3分钟');
};

// 停止船舶告警检查
const stopShipAlarmCheck = () => {
  if (shipAlarmInterval.value !== null) {
    clearInterval(shipAlarmInterval.value);
    shipAlarmInterval.value = null;
  }
};

// 添加clearDrawInteractions函数定义
// 清除绘图交互
function clearDrawInteractions() {
  if (activeDrawInteraction) {
    map.value.removeInteraction(activeDrawInteraction);
    activeDrawInteraction = null;
  }
  
  if (activeSelectInteraction) {
    map.value.removeInteraction(activeSelectInteraction);
    activeSelectInteraction = null;
  }
  
  if (measureTooltipElement && measureTooltipElement.parentNode) {
    measureTooltipElement.parentNode.removeChild(measureTooltipElement);
    measureTooltipElement = null;
  }
  
  if (measureTooltip) {
    map.value.removeOverlay(measureTooltip);
    measureTooltip = null;
  }
}

// 工具栏功能
const toggleSearchBox = () => {
  showSearchBox.value = !showSearchBox.value;
};

const showEnforcementShips = () => {
  showGaShipList.value = true;
};

const closeGaShipList = () => {
  showGaShipList.value = false;
};

// 添加新的响应式变量
const isToolbarCollapsed = ref(false);

// 添加新的方法
const toggleToolbar = () => {
  isToolbarCollapsed.value = !isToolbarCollapsed.value;
};

const toggleSidebar = () => {
  // 无论当前状态如何，都先设置类型
  PopupType.value = "leftContent";
  
  // 如果当前是关闭状态，则在打开时重置所有状态
  if (!isPopupRight.value) {
    isSidebarDrawer.value = false; // 重置抽屉状态
  }
  
  // 切换显示状态
  isPopupRight.value = !isPopupRight.value;
};

</script>

<style scoped lang="less">
.head-txt {
  font-size: 20px;
  color: #fff;
  margin-left: 10px;
  white-space: nowrap;
}

.head-right {
  height: 100%;
  display: flex;
  flex-direction: row;
  align-items: center;
  flex: 1;
  justify-content: flex-end;

  span:nth-of-type(1) {
    height: 100%;
  }
}

.head-right-flex {
  height: 100%;
  display: flex;
  flex-direction: row;
  align-items: center;

  span:nth-of-type(1) {
    height: 100%;
  }
}

.head-right-txt {
  line-height: 100%;
  font-size: 16px;
  margin-right: 10px;
  color: #c4c4c4;
  cursor: pointer;
}

.head-right-txt1 {
  line-height: 100%;
  font-size: 16px;
  margin-right: 15px;
  color: #fff;
  cursor: pointer;
}

.head-right-txt3 {
  line-height: 100%;
  font-size: 12px;
  margin-right: 15px;
  color: #fff;
  margin-bottom: 10px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  -o-text-overflow: ellipsis;
}

.head-right-line {
  width: 1px;
  height: 100%;
  background: #c4c4c4;
  margin: 0 15px;
}

.hoverline:hover {
  .hoverlinechild {
    text-decoration: underline;
  }
}


.top-nav-buttons {
  position: absolute;
  top: 15px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 1000;
  background-color: rgba(48, 65, 86, 0.85); /* 与侧边栏保持一致的背景色 */
  padding: 5px 10px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.3);
  backdrop-filter: blur(5px); /* 添加模糊效果 */
}

.top-nav-buttons .el-button-group {
  display: flex;
}

.top-nav-buttons .el-button--primary {
  background-color: rgba(31, 45, 61, 0.9);
  border-color: rgba(31, 45, 61, 0.9);
  color: #bfcbd9;
  transition: all 0.3s;
  padding: 8px 15px;
}

.top-nav-buttons .el-button--primary:hover,
.top-nav-buttons .el-button--primary:focus {
  background-color: #263445;
  border-color: #263445;
  color: #f4f4f5;
}

.top-nav-buttons .el-button--primary.active {
  background-color: rgba(64, 158, 255, 0.2);
  border-color: #409eff;
  color: #f4f4f5;
}
</style>

<style lang="less">
.elPopover.el-popper {
  color: #fff;
  background: #3c4167;
  margin-top: 0;
}

// 移除 .map 的 margin-right 和 transition
.map {
  width: 100%; // 宽度占满父容器
  height: 100%; // 高度占满父容器
  :deep(.dark-layer) {
    filter: blur(0px) grayscale(0%) sepia(100%) invert(95%) saturate(0%);
  }
  :deep(.label-layer) {
    filter: invert(100%) brightness(250%);
  }
  :deep(.light-layer) {
    filter: brightness(100%) saturate(100%);
  }
}
</style>

<style scoped src="@/assets/datePark.css"></style>
<style scoped src="@/assets/index.css"></style>

<style scoped>
.popup-container {
  position: absolute;
  top: 0;
  right: 0;
  width: 0;
  height: 0;
  z-index: 1000;
  pointer-events: none;
  transition: all 0.3s ease-in-out;
}

.popup-container > * {
  pointer-events: auto;
}

.popup-container.collapsed :deep(.content) {
  transform: translateX(100%);
  opacity: 0;
  visibility: hidden;
}

.collapse-button {
  position: absolute;
  left: -90px; /* 增加宽度以容纳文本 */
  top: 50%;
  margin-top: 20px;
  transform: translateY(-50%);
  width: 90px; /* 增加宽度 */
  height: 40px;
  background-color: rgba(187, 226, 236, 0.3);
  border-radius: 4px 0 0 4px;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  z-index: 1010;
  color: #646464;
  box-shadow: -2px 0 5px rgba(0, 0, 0, 0.3);
  transition: all 0.3s ease;
  padding: 0 10px;
  border-left: 3px solid #409eff;
}

.collapse-button:hover {
  background-color: rgba(64, 158, 255, 0.3);
  color: #fff;
  width: 100px;
}

.collapse-button i {
  font-size: 18px;
  transition: transform 0.3s;
  margin-right: 5px;
}

.collapse-button:hover i {
  transform: scale(1.1);
}

/* 测量工具提示样式 */
.tooltip {
  position: relative;
  background: rgba(0, 0, 0, 0.7);
  border-radius: 4px;
  color: white;
  padding: 4px 8px;
  white-space: nowrap;
  font-size: 12px;
  opacity: 0.7;
  position: relative;
  pointer-events: none;
}

.tooltip-measure {
  opacity: 1;
  font-weight: bold;
}

.tooltip-measure:before {
  border-top: 6px solid rgba(0, 0, 0, 0.7);
  border-right: 6px solid transparent;
  border-left: 6px solid transparent;
  content: "";
  position: absolute;
  bottom: -6px;
  margin-left: -6px;
  left: 50%;
}

/* 电子围栏样式 */
.fence-control {
  position: absolute;
  top: 15px;
  right: 15px;
  z-index: 1000;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.fence-button {
  width: 40px;
  height: 40px;
  background-color: rgba(64, 158, 255, 0.8);
  border-radius: 4px;
  display: flex;
  justify-content: center;
  align-items: center;
  color: white;
  cursor: pointer;
  font-size: 20px;
  transition: all 0.3s;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.fence-button:hover {
  background-color: rgba(64, 158, 255, 1);
  transform: scale(1.05);
}

.fence-panel {
  position: absolute;
  top: 70px;
  right: 15px;
  width: 300px;
  background-color: white;
  border-radius: 4px;
  padding: 15px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  z-index: 1000;
}

.fence-panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 10px;
}

.fence-panel-header h3 {
  margin: 0;
  font-size: 16px;
  color: #303133;
}

.fence-panel-content {
  margin-bottom: 15px;
}

.fence-panel-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 绘制样式 */
.ol-draw-tooltip {
  position: absolute;
  background: rgba(0, 0, 0, 0.6);
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  white-space: nowrap;
  user-select: none;
  pointer-events: none;
  z-index: 1100;
}

/* 闪烁动画 - 用于新创建的围栏 */
@keyframes fence-blink {
  0% { opacity: 0.4; }
  50% { opacity: 0.9; }
  100% { opacity: 0.4; }
}

.new-fence {
  animation: fence-blink 2s infinite;
}

/* 悬浮工具栏样式 */
.floating-toolbar {
  position: absolute;
  top: 15px;
  right: 15px;
  z-index: 1001;
  display: flex;
  background-color: white;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  width: auto;
}

.toolbar-collapsed .toolbar-item {
  display: none;
}

.toolbar-item {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  cursor: pointer;
  color: #606266;
  transition: all 0.3s;
  white-space: nowrap;
}

.toolbar-item:not(:last-child) {
  border-right: 1px solid #ebeef5;
}

.toolbar-item:hover {
  background-color: #f5f7fa;
  color: #409eff;
}

.toolbar-item .el-icon {
  font-size: 18px;
  margin-right: 5px;
}

.toolbar-collapse {
  padding: 10px;
  cursor: pointer;
  color: #606266;
  transition: all 0.3s;
  border-left: 1px solid #ebeef5;
  display: flex;
  justify-content: center;
  align-items: center;
}

.toolbar-collapse:hover {
  background-color: #f5f7fa;
  color: #409eff;
}

.toolbar-collapse .el-icon {
  font-size: 20px;
}


/* 搜索框样式 - 添加 right 过渡 */
.search-box {
  position: absolute;
  top: 15px;
  right: 15px;
  z-index: 1002;
  background-color: white;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 10px 15px;
  width: 400px;
  animation: slideIn 0.3s ease-in-out;
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.search-input {
  display: flex;
  align-items: center;
  width: 100%;
  gap: 8px;
}

.search-input .el-icon {
  color: #909399;
  font-size: 16px;
}

.search-input input {
  flex: 1;
  border: none;
  outline: none;
  padding: 5px 0;
  color: #606266;
  background: transparent;
  font-size: 14px;
}

.search-actions {
  display: flex;
  gap: 12px;
}

.search-actions .el-button {
  padding: 8px;
  background: transparent !important;
  border: none !important;
  box-shadow: none !important;
}

.search-actions .el-icon {
  margin: 0;
  font-size: 20px;
  color: #606266;
  transition: all 0.3s;
}

.search-actions .el-button:hover .el-icon {
  color: #409eff;
  transform: scale(1.2);
}

/* rightContent 容器样式 - 添加 right 过渡 */
:deep(.right-content-container) { /* 假设 rightContent 组件有根元素 */
  position: absolute;
  top: 70px; /* 或其他合适的位置 */
  right: 15px;
  z-index: 1000;
}

/* 主要布局样式 */
.layout {
  position: relative;
  width: 100%;
  height: 100vh; /* 确保占满视口高度 */
  overflow: hidden;
}

.main-content {
  width: 100%; /* 宽度占满100% */
  height: 100%;
  position: relative;
  overflow: hidden;
}

/* 其他可能需要调整的绝对定位元素 */
.last-message-box {
    position: fixed;
    bottom: 20px;
    right: 320px; /* 侧边栏宽度 + 间距 */
    z-index: 1000;
    padding: 12px;
    font-size: 12px;
}

.infoWindow {
  position: absolute;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 10px;
  border-radius: 4px;
  z-index: 1001; /* 比地图高 */
  pointer-events: none; /* 默认不捕获事件 */
  font-size: 12px;
  min-width: 150px;
}

.infoWindow_title {
  font-weight: bold;
  margin-bottom: 5px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.5);
  padding-bottom: 5px;
}

.infoWindow_text {
  display: flex;
  justify-content: space-between;
  margin-bottom: 3px;
}

/* 确保其他弹窗如 el-dialog, historical, dispose-log 等的样式和定位不受影响 */

</style>
